package com.fansl.koala.quickdev.component.message.email;

import cn.hutool.core.util.StrUtil;
import com.fansl.koala.quickdev.common.bean.entity.SendMailMessage;
import com.fansl.koala.quickdev.common.bean.po.SendMailMessagePo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author fansl
 * @Description: 账户激活消息模板
 * @date 2020/3/18 17:44
 */
@Slf4j
@Component
public class AccountActivationTemplateExecutor implements EmailMessageTemplateExecutor{
    @Resource
    private TemplateEngine templateEngine;

    @Value("${user.activation.baseUrl}")
    private String userActivationBaseUrl;
    /**
     * 创建消息模板
     *
     * @param mailMessage 邮箱消息内容
     * @throws Exception 异常信息
     */
    @Override
    public SendMailMessage createMessageTemplate(SendMailMessagePo mailMessage) throws Exception {
        SendMailMessage sendMailMessage = new SendMailMessage();
        //收件人
        sendMailMessage.setReceiver(mailMessage.getReceiver());
        Assert.isTrue(StrUtil.isNotBlank(userActivationBaseUrl),"发送激活码地址参数未配置");
        //生成激活链接
        String activationUrl = userActivationBaseUrl + "?username=%s&code=%s";
        Map<String,Object> extendParam =  mailMessage.getExtendParam();
        activationUrl = String.format(activationUrl,extendParam.get("username"),extendParam.get("code"));
        //返回内容
        sendMailMessage.setReturnContent(activationUrl);
        //邮件正文
        sendMailMessage.setContent(createContent(activationUrl));
        //邮件标题
        sendMailMessage.setSubject(createSubject(mailMessage));
        return sendMailMessage;
    }

    private String createContent(String activationUrl) {
        Context context = new Context();
        context.setVariable("activationUrl", activationUrl);
        return templateEngine.process("accountActivation", context);
    }

    private String createSubject(SendMailMessagePo mailMessage) {
        return mailMessage.getEmailMessageType().getDescription();
    }
}
